﻿using System;
using System.IO;
using FtpSupport;
using System.Web.Mvc;
using System.Configuration;
using SilenthinkCommon.Extension;
using System.Text.RegularExpressions;
using SilenthinkCommon.Configuration;

namespace Web.Manage.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Upload()
        {
            const string inputname = "filedata";
            var err = string.Empty;
            var localname = string.Empty;
            var disposition = Request.ServerVariables["HTTP_CONTENT_DISPOSITION"];

            bool result;
            string extension;
            var fullPath = string.Empty;

            var dr = DateTime.Now.ToString("yyyy/MM/dd");
            dr = dr.StartsWith("/") ? dr : string.Format("/{0}", dr);
            dr = dr.EndsWith("/") ? dr : string.Format("{0}/", dr);

            var guid = Guid.NewGuid().ToString("N");

            if (disposition != null)
            {
                localname = Regex.Match(disposition, "filename=\"(.+?)\"").Groups[1].Value;// 读取原始文件名
                extension = !string.IsNullOrEmpty(localname)
                                ? localname.Substring(localname.LastIndexOf('.')).ToLower()
                                : string.Empty;
                var remoteFile = string.Format("{0}{1}", guid, extension);

                using (var stream = Request.InputStream)
                {
                    result = FtpFile(stream, dr,ref remoteFile);
                    if (result)
                    {
                        fullPath =  remoteFile;
                    }
                    else
                    {
                        err = "上传失败";
                    }
                }
                return Json(new { err, msg = new { url = fullPath, localname } });

            }
            else
            {
                var filecollection = Request.Files;
                var postedfile = filecollection[inputname];
                if (postedfile != null)
                {
                    // 读取原始文件名
                    localname = postedfile.FileName;
                    extension = !string.IsNullOrEmpty(localname)
                                    ? localname.Substring(localname.LastIndexOf('.')).ToLower()
                                    : string.Empty;
                    var remoteFile = string.Format("{0}{1}", guid, extension);

                    using (var stream = postedfile.InputStream)
                    {
                        result = FtpFile(stream, dr,ref remoteFile);
                        if (result)
                        {
                            fullPath = remoteFile;
                        }
                        else
                        {
                            err = "上传失败";
                        }
                    }
                }
                var o = new { err, msg = new { url = fullPath, localname } };
                return Content(o.ToJson());
            }
        }
        protected static bool FtpFile(Stream stream, string dr,ref string remoteFile)
        {
            var ftpConfig = ConfigurationManager.GetSection("ftp.config") as FtpConfigurationSetion;
            if (ftpConfig != null)
            {
                using (var ftp = new FtpConnection(ftpConfig.Ip, ftpConfig.UserName, ftpConfig.Password))
                {
                    try
                    {
                        var temp = string.Empty;
                        dr.Split('/').ForEach(o => {
                            temp += string.Format("{0}/", o);
                            if (!ftp.DirectoryExist(temp))
                            {
                                ftp.CreateDirectory(temp);
                            }
                        });
                        ftp.SetCurrentDirectory(dr);
                        ftp.PutStream(stream, remoteFile);
                        remoteFile = ftpConfig.Server +dr+ remoteFile;
                        return true;
                    }
                    catch (Exception e)
                    {
                        return false;
                    }
                }
            }
            return false;
        }
    }
}
